package net.betou.trade.main.dao.impl;

import java.util.List;

import net.betou.common.hibernate3.Finder;
import net.betou.common.hibernate3.HibernateBaseDao;
import net.betou.common.page.Pagination;
import net.betou.trade.entity.main.Channel;
import net.betou.trade.main.dao.ChannelDao;

import org.springframework.stereotype.Repository;

@Repository
public class ChannelDaoImpl extends HibernateBaseDao< Channel, Integer > implements ChannelDao{

	@Override
	protected Class< Channel > getEntityClass( ) {
		return Channel.class;
	}

	public Channel deleteById( Integer id ) {
		Channel channel = get( id );
		if( channel != null ){
			getSession( ).delete( channel );
		}
		
		return channel;
	}

	public Channel findById( Integer id ) {
		return get(id);
	}

	public Channel save( Channel bean ) {
		getSession( ).save( bean );
		return bean;
	}
	
	public Pagination getPage( Integer selfId, String searchProperty, String searchValue, String orderProperty, String orderDirection, int pageNo, int pageSize ){
		
		Finder f = Finder.create( " from Channel bean where 1=1 " );
		if( selfId != null ){
			f.append( " and bean.admin.id=:id" );
			f.setParam( "id", selfId );
		}
		createSearch( f, searchProperty, searchValue );
		createOrder( f, orderProperty, orderDirection, "id" );
		
		return find( f, pageNo, pageSize );
	}
	
	@SuppressWarnings( "unchecked" )
	public List< Channel > getList( Integer selfId ){
		
		Finder f = Finder.create( " from Channel bean where 1=1 " );
		boolean setParam = false;
		
		if( selfId != null ){
			f.append( " and bean.admin.id=:id" );
			f.setParam( "id", selfId );
			setParam = true;
		}
		
		f.setCacheable( true ); // 加入缓存
		
		return find( f, setParam );
	}
	
	@SuppressWarnings( "unchecked" )
	public List< Channel > getOrientedGroupList( List< Integer > idList ){

		Finder f = Finder.create( "from Channel bean where 1=1 and " );
		f.append( "(" );
		for( int i = 0; i < idList.size( ); i++ ){
			f.append( " bean.admin.id=:adminId" + i );
			f.setParam( "adminId" + i, idList.get( i ) );
			
			if( i < idList.size( ) - 1 ){
				f.append( " or " );
			}
		}
		
		f.append( ")" );
		
		return find( f, true );
		
	}
	
	public Channel findMyChannel( Integer id, Integer selfId ){
		String hql = "from Channel bean where bean.id=? and bean.admin.id=?";
		return ( Channel ) this.findUnique( hql, id, selfId );
		
	}

}